type DefaultValueConfig = { has: true; defaultValue: string } | { has: false };

type EnvName =
  | 'COOKIE_SECURE'
  | 'JWT_SECRET'
  | 'JWT_ISSUER'
  | 'NODE_ENV'
  | 'REDIS_HOST'
  | 'REDIS_PORT'
  | 'SERVICE_NAME';

const E: Record<EnvName, DefaultValueConfig> = {
  COOKIE_SECURE: { has: true, defaultValue: 'false' },
  JWT_SECRET: { has: false },
  JWT_ISSUER: { has: true, defaultValue: 'paimon' },
  NODE_ENV: { has: true, defaultValue: 'development' },
  REDIS_HOST: { has: true, defaultValue: 'localhost' },
  REDIS_PORT: { has: true, defaultValue: '6379' },
  SERVICE_NAME: { has: true, defaultValue: 'charlotte' },
};

export function getServerEnv(name: EnvName): string {
  if (name in E) {
    const value = process.env[name];
    if (value === undefined) {
      const dvc = E[name];
      if (dvc.has) {
        return dvc.defaultValue;
      } else {
        throw new Error(`env ${name} is missing`);
      }
    }
    return value;
  } else {
    throw new Error(`env ${name} is not pre-defined`);
  }
}
